package com.agent.gateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * 请求日志过滤器
 *
 * @author Jeff_Wan
 * @description 记录请求和响应的基本信息
 */
@Slf4j
@Component
public class RequestLoggingFilter extends AbstractGatewayFilterFactory<RequestLoggingFilter.Config> {

    public RequestLoggingFilter() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            long startTime = System.currentTimeMillis();

            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                long duration = System.currentTimeMillis() - startTime;
                log.info("Request: {} {} | Status: {} | Duration: {}ms",
                        exchange.getRequest().getMethod(),
                        exchange.getRequest().getPath(),
                        Objects.requireNonNull(exchange.getResponse().getStatusCode()).value(),
                        duration);
            }));
        };
    }

    /**
     * 过滤器配置类
     */
    public static class Config {
        // 可配置参数
    }
}